package com.example.administrator.meishi.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;


import com.alibaba.fastjson.JSON;
import com.example.administrator.meishi.Movie;
import com.example.administrator.meishi.R;
import com.example.administrator.meishi.RefreshableView;

import com.example.administrator.meishi.adapter.PullAdapter1;
import com.example.administrator.meishi.bean.Video;
import com.example.administrator.meishi.utils.Httputils;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.lidroid.xutils.ViewUtils;


import java.util.List;


public class FragmentHOT extends Fragment {
    private View view = null;
    //这是一个fragment工厂可以用来创建新的并接受一切接口进行解析
    private List<Video> videos;
    private RefreshableView re;
    int page=1;
    public Handler handler=new Handler(){
        //将数据传递给适配器
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            list = (List<Video>) msg.obj;
            Log.i("Tag","....................."+list.size());
            PullAdapter1 adapter1=new PullAdapter1(getContext());
            adapter1.setData(list);
            pull.setAdapter(adapter1);


        }
    };
    private String path;
    private PullToRefreshGridView mPull;
    private PullToRefreshGridView pull;
    private GridView g;
    private Message msg;
    private String str="&&page=%d&count";
    private List<Video> list;

    public FragmentHOT() {
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater = getActivity().getLayoutInflater();
        view = inflater.inflate(R.layout.fragment_fragment1, (ViewGroup) getActivity().findViewById(R.id.study_viewpager), false);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ViewGroup p = (ViewGroup) view.getParent();
        if (p != null) {
            p.removeAllViewsInLayout();
        }
        ViewUtils.inject(this, view);
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser){
        }else {
        }
    }
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //找到控件
        pull = (PullToRefreshGridView) view.findViewById(R.id.pull_refresh_grid);
        pull.setScrollingWhileRefreshingEnabled(true);
        g = pull.getRefreshableView();
        g.setNumColumns(2);
        //接收的数据进行解析
        new Thread(){
           @Override
           public void run() {
               Bundle bundle=getArguments();
               String path = bundle.getString("pos");
               byte[] date = Httputils.getpath(path);
               String str = new String(date);
               videos = JSON.parseArray(str, Video.class);
               msg = new Message();
               msg.obj=videos;
               handler.sendMessage(msg);
           }
       }.start();
        //设置上啦加载下拉刷新
        loadLisener();
        //设置点击
        pullOnClick();
    }

    private void loadLisener() {
        //设置上下拉模式
        pull.setMode(PullToRefreshBase.Mode.BOTH);
        pull.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            private String s2;
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {

                String label = DateUtils.formatDateTime(
                        getActivity(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy()
                        .setLastUpdatedLabel(label);
                StringBuilder builder = new StringBuilder();
                final String s = builder.append(path).append(str).toString();
                page += 1;
                String s1 = Integer.toString(page);
                s2 = s.replaceAll("%d", s1);
                if (page <= 200) {
                    new Thread() {
                        @Override
                        public void run() {
                            byte[] date = Httputils.getpath(path);
                            String str = new String(date);
                            videos = JSON.parseArray(str, Video.class);
                            msg = new Message();
                            msg.obj = videos;
                            handler.sendMessage(msg);
                        }
                    }.start();
                } else {
                    Toast.makeText(getActivity(), "没有更多数据了", Toast.LENGTH_SHORT).show();
                }
                //停止刷新操作
                pull.onRefreshComplete();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                StringBuilder builder = new StringBuilder();
                final String s = builder.append(path).append(str).toString();
                page += 1;
                String s1 = Integer.toString(page);
                s2 = s.replaceAll("%d", s1);
                if (page <= 10) {
                    new Thread() {
                        @Override
                        public void run() {
                            byte[] date = Httputils.getpath(path);
                            String str = new String(date);
                            videos = JSON.parseArray(str, Video.class);
                            msg = new Message();
                            msg.obj = videos;
                            handler.sendMessage(msg);
                        }
                    }.start();
                } else {
                    Toast.makeText(getActivity(), "没有更多数据了", Toast.LENGTH_SHORT).show();
                }
                pull.onRefreshComplete();//停止刷新操作
            }
        });
    }


    //设置点击事件
    private void pullOnClick() {
        pull.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               Video video = (Video) g.getItemAtPosition(position);
                if (video.getMedia().getVideo() != null){
                    Intent intent = new Intent(getActivity(), Movie.class);
                    intent.putExtra("video",video);
                    startActivity(intent);
                }else {
                    Toast.makeText(getActivity(), "无视频", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    }

